package com.wangyadong.hobby.schedule.jobtask.dsa.binaryTree;

import java.util.ArrayList;
import java.util.List;

public abstract class BinaryAbstractTree<E>
        extends AbtractTree<E>
        implements BinaryTree<E> {


    @Override
    public Position<E> sibling(Position<E> position) throws IllegalArgumentException {

        Position parent = parent(position);
        if (parent == null) {
            return null;
        }

        if (parent != left(position)) {
            return right(position);
        } else {
            return left(position);
        }


    }

    @Override
    public int numChildren(Position<E> position) throws IllegalArgumentException {

        int count = 0;
        Position<E> left = left(position);
        if (left != null) {
            count++;
        }
        Position<E> right = right(position);
        if (right != null) {
            count++;
        }
        return count;
    }

    @Override
    public Iterable<Position<E>> children(Position<E> position) throws IllegalArgumentException {
        List<Position<E>> snapshot = new ArrayList();
        Position<E> left = left(position);
        if (left != null) {
            snapshot.add(left);
        }
        Position<E> right = right(position);
        if (right != null) {
            snapshot.add(right);
        }
        return snapshot;
    }

    public void inOrderSubTree(Position<E> position, List<Position<E>> snapshot) {
        Position<E> left = left(position);
        if (left != null) {
            inOrderSubTree(left, snapshot);
        }
        snapshot.add(left);
        if (right(position) != null) {
            inOrderSubTree(right(position), snapshot);
        }
    }
}
